﻿using System;
using System.IO;
using System.Net;
using System.Threading;

namespace MotodeServer_Win
{
    /// <summary>
    /// This class handles basic web request listening and passes the data off to the handler(s)
    /// </summary>
    class WebListener
    {
        private HttpListener listener;
        private StreamWriter sw;
        private Thread thread;
        private HttpListenerContext context;

        public WebListener()
        {
            listener = new HttpListener();
            listener.Prefixes.Add("http://localhost/Motode/");
            
            thread = new Thread(Loop);
        }

        /// <summary>
        /// Starts the listener for data
        /// </summary>
        public void Start()
        {
            if (thread.IsAlive)
            {
                thread.Abort();
            }

            listener.Start();
            thread.Start();
        }

        /// <summary>
        /// Stops the listener
        /// </summary>
        public void Stop()
        {
            if (sw != null)
            {
                sw.Close();
            }
            listener.Stop();
            thread.Abort();
        }

        /// <summary>
        /// The main loop listening for requests
        /// </summary>
        private void Loop()
        {
            while (true)
            {
                //get the new context for the request and a new streamwriter
                context = listener.GetContext();
                sw = new StreamWriter(context.Response.OutputStream);
                context.Response.ContentType = "text";
                context.Response.StatusCode = 200;

                //get the data
                string requestUrl = context.Request.RawUrl;
                sw.WriteLine("The URL was {0}", requestUrl);
                //Console.WriteLine("The URL was {0}", requestUrl);

                //close the streamwriter
                sw.Close();
            }
        }
    }
}
